package com.igeek.boot.config;

import cn.hutool.core.collection.CollectionUtil;
import com.igeek.boot.entity.Admin;
import com.igeek.boot.entity.Permission;
import com.igeek.boot.entity.Role;
import lombok.Data;
import lombok.ToString;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Set;

/**
 * @Author fengqq
 * @Description UserDetails 是security提供的存储认证用户信息的接口
 * @Date 2024/9/13  15:20
 */
@Data
@ToString
public class LoginUser implements UserDetails {
    private Admin admin;

    public LoginUser(Admin admin) {
        this.admin = admin;
    }

    private List<GrantedAuthority> authorities;

    //获取角色信息列表
    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        if(CollectionUtil.isNotEmpty(authorities)){
            return authorities;
        }
        //权限列表为空时 才需要进行遍历
        authorities = new ArrayList<GrantedAuthority>();
        //添加角色和权限
        Set<Role> roles = admin.getRoles();
        roles.forEach(role -> {
            //添加角色
            authorities.add(new SimpleGrantedAuthority("ROLE_"+role.getRoleName()));
            Set<Permission> permissions = role.getPermissions();
            permissions.forEach(permission -> {
                //添加权限
                authorities.add(new SimpleGrantedAuthority(permission.getPermissionName()));
            });
        });
        return authorities;
    }

    //获取认证的用户密码 加密过的
    @Override
    public String getPassword() {
        return admin.getPassword();
    }

    //获取认证的用户名称
    @Override
    public String getUsername() {
        return admin.getUsername();
    }
    //帐户是否过期
    @Override
    public boolean isAccountNonExpired() {
        return true;
    }
    //帐户是否锁定
    @Override
    public boolean isAccountNonLocked() {
        return true;
    }
    //凭证是否过期
    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    //用户是否可用 状态0 未开启 1 开启
    @Override
    public boolean isEnabled() {
        return admin.getStatus()==1;
    }
}
